import { useState, useEffect, useCallback } from 'react';
import { College } from '../mock/collegeData';
import { collegeService } from '../services/CollegeService';

interface UseCollegeManagementOptions {
  initialSearchTerm?: string;
  initialPageSize?: number;
}

export interface CollegeFormData {
  name: string;
  dean: string;
  location: string;
  contactNumber: string;
  description: string;
  departmentCount: string;
  studentCount: string;
  teacherCount: string;
  establishedYear: string;
}

export const useCollegeManagement = ({ 
  initialSearchTerm = '', 
  initialPageSize = 10 
}: UseCollegeManagementOptions = {}) => {
  // 核心数据状态
  const [colleges, setColleges] = useState<College[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // 搜索和分页状态
  const [searchTerm, setSearchTerm] = useState(initialSearchTerm);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(initialPageSize);
  
  // 选择状态
  const [selectedColleges, setSelectedColleges] = useState<number[]>([]);
  const [selectAll, setSelectAll] = useState(false);
  
  // 筛选和分页后的数据
  const filteredColleges = colleges.filter(college => 
    !searchTerm ||
    college.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    college.dean.toLowerCase().includes(searchTerm.toLowerCase()) ||
    college.location.toLowerCase().includes(searchTerm.toLowerCase())
  );
  
  const totalPages = Math.ceil(filteredColleges.length / pageSize);
  const paginatedColleges = filteredColleges.slice(
    (currentPage - 1) * pageSize, 
    currentPage * pageSize
  );
  
  // 加载学院数据
  const loadColleges = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await collegeService.getColleges();
      setColleges(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载数据失败');
    } finally {
      setLoading(false);
    }
  }, []);
  
  // 初始化加载
  useEffect(() => {
    loadColleges();
  }, [loadColleges]);
  
  // 搜索变化时重置到第一页
  useEffect(() => {
    setCurrentPage(1);
    setSelectedColleges([]);
    setSelectAll(false);
  }, [searchTerm]);
  
  // 批量删除
  const batchDelete = useCallback(async () => {
    if (selectedColleges.length === 0) return;
    
    try {
      setLoading(true);
      setError(null);
      
      // 并行删除
      const deletePromises = selectedColleges.map(id => collegeService.deleteCollege(id));
      await Promise.all(deletePromises);
      
      // 重新加载数据
      await loadColleges();
      
      // 重置选择状态
      setSelectedColleges([]);
      setSelectAll(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : '批量删除失败');
    } finally {
      setLoading(false);
    }
  }, [selectedColleges, loadColleges]);
  
  // 选择/取消选择学院
  const toggleCollegeSelection = useCallback((id: number) => {
    setSelectedColleges(prev => 
      prev.includes(id) 
        ? prev.filter(collegeId => collegeId !== id)
        : [...prev, id]
    );
  }, []);
  
  // 全选/取消全选
  const toggleSelectAll = useCallback(() => {
    if (selectAll) {
      setSelectedColleges([]);
    } else {
      setSelectedColleges(filteredColleges.map(college => college.id));
    }
    setSelectAll(!selectAll);
  }, [selectAll, filteredColleges]);
  
  // 计算统计数据
  const stats = {
    total: colleges.length,
    studentTotal: colleges.reduce((sum, college) => sum + college.studentCount, 0),
    teacherTotal: colleges.reduce((sum, college) => sum + college.teacherCount, 0),
    departmentTotal: colleges.reduce((sum, college) => sum + college.departmentCount, 0)
  };
  
  return {
    // 数据
    colleges,
    filteredColleges,
    paginatedColleges,
    loading,
    error,
    
    // 状态
    searchTerm,
    currentPage,
    pageSize,
    totalPages,
    selectedColleges,
    selectAll,
    stats,
    
    // 服务实例
    service: collegeService,
    
    // 操作方法
    setSearchTerm,
    setCurrentPage,
    setPageSize,
    toggleCollegeSelection,
    toggleSelectAll,
    batchDelete,
    loadColleges
  };
};